package com.eos.common.tool;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.hf.utils.StringUtil;

/**
 * 数据访问层对象池 业务层获取数据DAO层对象的工厂类 系统启动时需要实例化 init方法 单例模式
 * 
 * @author Administrator
 * 
 */
public class DaoAccessObjectPoolContextFactory {
	private static Map<String, Object> ormDaoObjectPoolMap = new HashMap<String, Object>();// orm_dao_bean.xml所有的DAO层对象池
	private static DaoAccessObjectPoolContextFactory daoAccessObjectPoolContextFactory = null;
	private Object obj = null;

	private DaoAccessObjectPoolContextFactory() {

	}

	public static DaoAccessObjectPoolContextFactory getInstaAccessObjectPoolContext() {
		if (null == daoAccessObjectPoolContextFactory) {
			daoAccessObjectPoolContextFactory = new DaoAccessObjectPoolContextFactory();
		}
		return daoAccessObjectPoolContextFactory;
	}

	/**
	 * 系统启动时需要实例化调用init方法
	 */
	public void init() {
		Iterator<String> iterator = WebStartServiceThread.dataAccessMap
				.keySet().iterator();
		try {
			while (iterator.hasNext()) {
				String key = StringUtil.NullToString(iterator.next())
						.toLowerCase();
				ormDaoObjectPoolMap
						.put(
								key,
								Class
										.forName(
												StringUtil
														.NullToString(WebStartServiceThread.dataAccessMap
																.get(key)))
										.newInstance());
			}
			System.out
					.println("*************系统加载数据访问层配置文件orm_dao_bean.xml完成...*********");
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 通过orm_dao_bean.xml的key获取数据访问层的对象
	 * 
	 * @param name
	 * @return 数据访问层的对象 需要强制类型转换
	 */
	public Object instanceDataAccessObject(String name) {
		obj = ormDaoObjectPoolMap.get(StringUtil.NullToString(name)
				.toLowerCase());
		if (null == obj) {
			try {
				obj = Class
						.forName(
								StringUtil
										.NullToString(WebStartServiceThread.dataAccessMap
												.get(StringUtil
														.NullToString(name).toLowerCase())))
						.newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

}
